# -*- coding: utf-8 -*-
"""
Web framework/Tornado WebSocket/test01.py
"""
import os
import tornado.web
import tornado.websocket
import asyncio


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("test01.html")


class IndexWebSocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin: str) -> bool:
        """
        WebSocketHandler.check_origin
        :param origin:
        :return:
        """
        return True

    def open(self):
        """
        WebSocketHandler.open
        :return:
        """
        self.write_message(f"WebSocket Opened.")

    def on_message(self, message):
        """
        WebSocketHandler.on_message
        :param message:
        :return:
        """
        self.write_message(f"Your send message is {message}.")

    def on_close(self) -> None:
        """
        WebSocketHandler.on_close
        :return:
        """
        print("WebSocket Closed.")


async def main():
    static_path = os.path.join(os.getcwd(), "static")
    template_path = os.path.join(os.getcwd(), "static")
    settings = {
        'static_path': static_path,
        'template_path': template_path
    }
    app = tornado.web.Application([
        (r"/", IndexHandler),
        (r"/websocket/", IndexWebSocketHandler),
    ], **settings)
    app.listen(8888)
    await asyncio.Event().wait()


if __name__ == '__main__':
    asyncio.run(main())
